<template>
  <div class="selectAddressPopup">
    <u-popup :closeable="true" :closeOnClickOverlay="true" :show="show" round="10px" mode="bottom" @close="close" @open="open">
      <view class="popup">
        <div class="top">
          <div class="title">
            <span class="text">请选择城市</span>
          </div>
        </div>
        <div class="tab">
          <div class="item" @click="clickTab(0)">{{ curProvince.fullname || "选择省" }}</div>
          <div class="item" v-if="curProvince && cityList.length > 0" @click="clickTab(1)">{{ curCity.fullname || "选择市" }}</div>
          <div class="item" v-if="curCity && countyList.length > 0" @click="clickTab(2)">{{ curCounty.fullname || "选择区" }}</div>
          <div class="item" v-if="curCounty && streetList.length > 0" @click="clickTab(3)">{{ curStreet.fullname || "选择街道" }}</div>
        </div>
        <div class="tab_line">
          <div class="active_line" :style="{ transform: `translateX(${translateX}px)` }"></div>
        </div>
        <div class="content_list" v-if="tabCurIndex == 0">
          <scroll-view scroll-y :scroll-into-view="goProvince" :style="{ height: '63vh' }">
            <div class="item" v-for="item in provinceList" :id="'province' + item.id" :key="item.id">
              <div class="letter">{{ item.letter }}</div>
              <div class="name" :class="[item.id == curProvince.id ? 'active' : '']" @click="clickItem('province', item)">{{ item.fullname }}</div>
            </div>
          </scroll-view>
        </div>
        <div class="content_list" v-if="tabCurIndex == 1">
          <scroll-view scroll-y :scroll-into-view="goCity" :style="{ height: '63vh' }">
            <div class="item" v-for="item in cityList" :id="'city' + item.id" :key="item.id">
              <div class="letter">{{ item.letter }}</div>
              <div class="name" :class="[item.id == curCity.id ? 'active' : '']" @click="clickItem('city', item)">{{ item.fullname }}</div>
            </div>
          </scroll-view>
        </div>
        <div class="content_list" v-if="tabCurIndex == 2">
          <scroll-view scroll-y :scroll-into-view="goCounty" :id="'county' + item.id" :style="{ height: '63vh' }">
            <div class="item" v-for="item in countyList" :key="item.id">
              <div class="letter">{{ item.letter }}</div>
              <div class="name" :class="[item.id == curCounty.id ? 'active' : '']" @click="clickItem('county', item)">{{ item.fullname }}</div>
            </div>
          </scroll-view>
        </div>
        <div class="content_list" v-if="tabCurIndex == 3">
          <scroll-view scroll-y :scroll-into-view="goStreet" :style="{ height: '63vh' }">
            <div class="item" v-for="item in streetList" :id="'street' + item.id" :key="item.id">
              <div class="letter">{{ item.letter }}</div>
              <div class="name" :class="[item.id == curStreet.id ? 'active' : '']" @click="clickItem('street', item)">{{ item.fullname }}</div>
            </div>
          </scroll-view>
        </div>
      </view>
    </u-popup>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  name: "selectAddressPopup",
  props: {
    show: {
      type: Boolean,
      default: true,
    },
    max: {
      type: Number,
      default: 1,
    },
    type: {
      type: String,
      default: "getLocation",
    },
    info: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      goProvince: "", //省份的锚点
      goCity: "", //城市的锚点
      goCounty: "", //区的锚点
      goStreet: "", //街道的锚点
      // show: false,
      tabCurIndex: 0,
      provinceList: [], //省份列表
      cityList: [], //城市列表
      countyList: [], //区县列表
      streetList: [], //街道列表
      curProvince: null, //当前省份
      curCity: null, //当前城市
      curCounty: null, //当前区县
      curStreet: null, //当前街道
      municipality: ["上海市", "北京市", "天津市", "重庆市"], //直辖市
      userLocationInfo: null,
    };
  },
  computed: {
    ...mapGetters("location", ["getUserLocationInfo"]),
    translateX() {
      if (this.tabCurIndex == 0) {
        return 22;
      } else if (this.tabCurIndex == 1) {
        return 95;
      } else if (this.tabCurIndex == 2) {
        return 170;
      } else if (this.tabCurIndex == 3) {
        return 246;
      }
    },
  },
  async onShow(options) {},
  async created() {
    await this.getProvinceList();
    if (this.getUserLocationInfo) {
      this.userLocationInfo = this.getUserLocationInfo;
      this.curProvince = {
        cdix: "",
        fullname: this.info.first_area_des,
        id: JSON.stringify(this.info.first_area_id),
        letter: "",
        location: {},
        name: this.info.first_area_des,
        pinyin: [],
      };
      if (this.info.first_area_id) {
        this.tabCurIndex = 0;
        this.getCityList(this.info.first_area_id, "city");
      }
      this.curCity = {
        fullname: this.info.second_area_des,
        id: JSON.stringify(this.info.second_area_id),
        letter: "",
        location: {},
        name: this.info.second_area_des,
        pinyin: [],
      };
      if (this.info.second_area_id) {
        this.tabCurIndex = 1;
        this.getCityList(this.info.second_area_id, "county");
      }
      this.curCounty = {
        fullname: this.info.third_area_des,
        id: JSON.stringify(this.info.third_area_id),
        letter: "",
        location: {},
        name: this.info.third_area_des,
        pinyin: [],
      };
      if (this.info.third_area_id) {
        this.tabCurIndex = 2;
        this.getCityList(this.info.third_area_id, "street");
      }
      if (this.info.four_area_id) {
        this.tabCurIndex = 3;
        this.curStreet = {
          fullname: this.info.four_area_des,
          id: JSON.stringify(this.info.four_area_id),
          letter: "",
          location: {},
          name: this.info.four_area_des,
          pinyin: [],
        };
      } else {
        this.curStreet = null;
      }
    }
  },
  methods: {
    clickTab(index) {
      switch (index) {
        case 0:
          this.curCity = null;
          this.curCounty = null;
          this.curStreet = null;
          this.cityList = [];
          this.countyList = [];
          this.streetList = [];
          console.log(this.cityList, this.countyList, this.streetList);
          break;
        case 1:
          this.curCounty = null;
          this.curStreet = null;
          this.countyList = [];
          this.streetList = [];
          break;
        case 2:
          this.curStreet = null;
          this.streetList = [];
          break;
        case 3:
          break;
      }
      this.tabCurIndex = index;
      this.$forceUpdate();
    },
    open() {
      // this.show = true;
    },
    close() {
      this.$emit("close");
      // this.show = false;
    },
    async clickItem(type, item) {
      switch (type) {
        case "province":
          //省
          this.curProvince = item;
          await this.getCityList(item.id, "city");
          if (this.cityList.length > 0) {
            this.tabCurIndex = 1;
          } else {
            this.$emit("getAddress", {
              province: this.curProvince,
              city: this.curCity,
              county: this.curCounty,
              street: this.curStreet,
            });
          }
          break;
        case "city":
          //市\
          this.curCity = item;
          await this.getCityList(item.id, "county");
          if (this.countyList.length > 0) {
            this.tabCurIndex = 2;
          } else {
            this.$emit("getAddress", {
              province: this.curProvince,
              city: this.curCity,
              county: this.curCounty,
              street: this.curStreet,
            });
          }
          break;
        case "county":
          // 区县
          this.curCounty = item;
          await this.getCityList(item.id, "street");
          if (this.streetList.length > 0) {
            this.tabCurIndex = 3;
          } else {
            this.$emit("getAddress", {
              province: this.curProvince,
              city: this.curCity,
              county: this.curCounty,
              street: this.curStreet,
            });
          }
          break;
        case "street":
          // 街道;
          this.curStreet = item;

          this.$emit("getAddress", {
            province: this.curProvince,
            city: this.curCity,
            county: this.curCounty,
            street: this.curStreet,
          });
          break;
      }
    },
    async getProvinceList() {
      let res = await this.$getMap.getProvinceList();
      try {
        this.provinceList = res;
        await this.chineseLetter(this.provinceList, "fullname");
        console.log(this.provinceList);
      } catch (error) {}
    },
    async sortArray(arr, dataLeven) {
      /* 获取数组元素内需要比较的值 */
      function getValue(option) {
        // 参数： option 数组元素
        if (!dataLeven) return option;
        var data = option;
        dataLeven.split(".").filter(function (item) {
          data = data[item];
        });
        return data + "";
      }
      arr.sort(function (item1, item2) {
        return getValue(item1).localeCompare(getValue(item2), "zh-CN");
      });
    },
    chineseLetter(arr, dataLeven) {
      var letter = "abcdefghjklmnopqrstwxyz".split("");
      var zh = "阿八嚓哒妸发旮哈讥咔垃痳拏噢妑七呥扨它穵夕丫帀".split("");
      /* 获取数组元素比较的值 */
      function getValue(option) {
        if (!dataLeven) return option;
        var data = option;
        dataLeven.split(".").filter(function (item) {
          data = data[item];
        });
        return data + "";
      }
      /* 进行排序 */
      arr.sort(function (item1, item2) {
        return getValue(item1).localeCompare(getValue(item2), "zh-Hans-CN");
      });
      /* 判断需要排序的字符串是否含有中文字符 */
      if (/[\u4e00-\u9fff]/.test(getValue(arr[0])) && typeof arr[0] === "object") pySegSort(0, 0);
      /* 给省列表中添加首字符 */
      function pySegSort(letterIndex, zhIndex) {
        var first = true; // 首次是否加 字母标识
        for (var i = zhIndex; i < arr.length; i++) {
          var item = arr[i];
          //      是否有值 && 当前值大于等于本次字母的最小值 && (最后一位 || 当前值小于下次字母的最小值)
          var state =
            zh[letterIndex] &&
            getValue(item).localeCompare(zh[letterIndex], "zh") >= 0 &&
            (letterIndex === letter.length - 1 || getValue(item).localeCompare(zh[letterIndex + 1], "zh") < 0);
          if (state) {
            // 满足条件，同一个首字母下的：例如 A 下的所有省份
            if (first) {
              //是否是第一次出现
              item.letter = letter[letterIndex].toUpperCase();
              first = false;
            } else {
              item.letter = "";
            }
          } else {
            // 递归调用 函数，进行下次字母下的排列
            letterIndex++;
            if (letterIndex < letter.length) {
              pySegSort(letterIndex, i);
              break;
            }
          }
        }
      }
    },
    async getCityList(id, type) {
      let list = await this.$getMap.getCityList(id);
      if (list.status && list.status == 363) {
        // this.$emit("getAddress", {
        //   province: this.curProvince,
        //   city: this.curCity,
        //   county: this.curCounty,
        //   street: this.curStreet,
        // });
        return false;
      }

      try {
        if (type == "city") {
          this.cityList = list;
          this.chineseLetter(this.cityList, "name");
        } else if (type == "county") {
          this.countyList = list;
          this.chineseLetter(this.countyList, "name");
        } else if (type == "street") {
          this.streetList = list;
          this.chineseLetter(this.streetList, "name");
        }
        console.log(list);
      } catch (error) {
        this.$emit("getAddress", {
          province: this.curProvince,
          city: this.curCity,
          county: this.curCounty,
          street: this.curStreet,
        });
      }
    },
    async location() {
      if (this.curProvince) {
        await this.getCityList(this.curProvince.id, "city");
        if (this.cityList.length > 0) {
          this.tabCurIndex = 1;
          this.goProvince = "province" + this.curProvince.id;
        } else {
          // this.$emit("getAddress", {
          //   province: this.curProvince,
          //   city: this.curCity,
          //   county: this.curCounty,
          //   street: this.curStreet,
          // });
        }
      }
      if (this.curCity && !this.municipality.includes(this.curCity.fullname)) {
        await this.getCityList(this.curCity.id, "county");
        if (this.countyList.length > 0) {
          this.tabCurIndex = 2;
          this.goCity = this.curCity.id;
        } else {
          // this.$emit("getAddress", {
          //   province: this.curProvince,
          //   city: this.curCity,
          //   county: this.curCounty,
          //   street: this.curStreet,
          // });
        }
      }
      if (this.curCounty) {
        await this.getCityList(this.curCounty.id, "street");
        if (this.streetList.length > 0) {
          this.tabCurIndex = 3;
          this.goCounty = this.curCounty.id;
        } else {
          // this.$emit("getAddress", {
          //   province: this.curProvince,
          //   city: this.curCity,
          //   county: this.curCounty,
          //   street: this.curStreet,
          // });
        }
      }
      if (this.curStreet) {
        this.goStreet = this.curStreet.id;
        // this.$emit("getAddress", {
        //   province: this.curProvince,
        //   city: this.curCity,
        //   county: this.curCounty,
        //   street: this.curStreet,
        // });
      }
    },
  },
  watch: {
    tabCurIndex: {
      handler(n, o) {
        console.log(398, n);
      },
      immediate: false,
    },
  },

  // 组件周期函数--监听组件挂载完毕
  mounted() {},
  // 组件周期函数--监听组件数据更新之前
  beforeUpdate() {},
  // 组件周期函数--监听组件数据更新之后
  updated() {},
  // 组件周期函数--监听组件激活(显示)
  activated() {},
  // 组件周期函数--监听组件停用(隐藏)
  deactivated() {},
  // 组件周期函数--监听组件销毁之前
  beforeDestroy() {},
};
</script>

<style scoped lang="scss">
.selectAddressPopup {
  .popup {
    height: 80vh;

    .top {
      width: 90%;
      height: 53px;
      line-height: 53px;
      display: flex;
      justify-content: space-between;
      margin: 0 auto;
      background: #fff;
      font-size: 16px;
      .title {
        width: 100%;
        font-family: PingFang SC-Semibold, PingFang SC;
        font-weight: 600;
        color: #333333;
        text-align: center;
        .num {
          font-size: 14px;
          font-family: PingFang SC-Regular, PingFang SC;
          font-weight: 400;
          color: #999999;
          margin-left: 10px;
        }
        .cur_ad {
          font-size: 14px;
          font-family: PingFang SC-Regular, PingFang SC;
          font-weight: 400;
          color: #333333;
          .iconfont {
            font-size: 14px;
            color: #ff8822;
            margin: 0 2px 0 11px;
          }
        }
        .address {
          margin-left: 6px;
          font-size: 14px;
          font-family: PingFang SC-Regular, PingFang SC;
          font-weight: 400;
          color: #ff8822;
        }
        .location_text {
          margin-left: 10px;
        }
      }
      .location_text {
        font-size: 14px;
        font-family: PingFang SC-Regular, PingFang SC;
        font-weight: 400;
        color: #ff8822;
      }
    }
    .tab {
      box-sizing: border-box;
      padding: 0 12px 12px 12px;
      display: flex;
      .item {
        width: 80px;
        font-size: 14px;
        color: #333;
        text-align: center;
        @include ells(1);
      }
    }
    .tab_line {
      height: 1px;
      width: 100%;
      background-color: #99999944;
      .active_line {
        height: 1px;
        width: 60px;
        background: #ff8822;
        transition: all 0.3s;
      }
    }
    .content_list {
      overflow-y: scroll;
      .item {
        line-height: 32px;
        font-size: 14px;
        color: #333;

        position: relative;
        display: flex;
        .letter {
          width: 20px;
          padding-left: 15px;
        }
        .name {
          padding-left: 28px;
        }
      }
    }
  }
  .active {
    color: #ff8822 !important;
  }
}
</style>
